<template>
  <div class="GdwyyAppSelectGrid">
    <div class="selected-grid">
      <div class="popup-ope flex-center flex-between font-14">
        <div @click="handleOpe('cancel')">取消</div>
        <div @click="handleOpe('submit')">确定</div>
      </div>
      当前选中营服：<span class="selected-grid-name">{{ selectdedNode.title || GRID_NAME }}</span>
      <a-input-search class="input-s" placeholder="搜索营服" @change="onInputSearch" v-model="inputGrid" />
    </div>
    <van-loading v-if="loading" type="spinner" color="#1989fa" />
    <div class="normal-list" v-else>
      <div :style="{ maxHeight: this.maxTreeHeight + 'px', overflow: 'auto' }">
        <a-tree :tree-data="treeData" :style="{ maxHeight: this.maxTreeHeight + 'px' }" @select="onTreeNodeSelect">
          <template slot="title" slot-scope="{ title }">
            <span v-if="title.indexOf(searchValue) > -1">
              {{ title.substr(0, title.indexOf(searchValue)) }}
              <span style="color: #f50">{{ searchValue }}</span>
              {{ title.substr(title.indexOf(searchValue) + searchValue.length) }}
            </span>
            <span v-else>{{ title }}</span>
          </template>
        </a-tree>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { USER_INFO } from '@/store/mutation-types'
import { postAction } from '@api/manage'
import { Toast } from 'vant'
const UA = window.navigator.userAgent.toLowerCase()
export default {
  name: 'GdwyyAppSelectGrid',
  props: {
    GRID_NAME: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      showPopup: false,
      selectdedNode: {
        title: '',
      },
      searchValue: '',
      treeData: [],
      gridList: [],
      formatTreeData: [],
      maxTreeHeight: 0,
      permissionOrgCode: '',
      inputGrid: '',
      loading: false,
    }
  },

  created() {
    const userInfo = Vue.ls.get(USER_INFO)
    const { datapermissionMap } = userInfo
    // this.permissionOrgCode = datapermissionMap[0].orgCode
    this.permissionOrgCode = datapermissionMap.map((k) => k.key).join('|')
    this.maxTreeHeight = Math.floor(window.innerHeight * 0.7)
    this.showDialog()
    // 没有网格信息or有多个网格信息, 跳转网格选择页面-展示全部网格
    // 判断是否为登录之后进入的此页面,如果是则 点击取消时 不能返回
  },

  methods: {
    showDialog() {
      this.showPopup = true
      this.selectdedNode.title = this.GRID_NAME
      // this.treeData = this.formatTreeData
      this.inputGrid = ''
      // if (this.treeData.length) return
      this.getGridList()
    },
    onTreeNodeSelect(sk, obj) {
      this.selectdedNode = obj.node.dataRef
      if (sk.length == 0) return (this.selectdedNode = {})
    },
    onInputSearch(e) {
      const value = e.target.value
      const filterGridList = []
      const filter = (data) => {
        for (const item of data) {
          if (item.GRID_NAME.indexOf(value) > -1) {
            filterGridList.push({
              key: item.GRID_ID,
              title: item.GRID_NAME,
              type: item.MARKET_TYPE_DESC,
              scopedSlots: { title: 'title' },
            })
          }
          if (item.children && item.children.length > 0) filter(item.children)
        }
      }
      filter(this.gridList)

      Object.assign(this, {
        searchValue: value,
        treeData: value == '' ? this.formatTreeData : filterGridList,
      })
    },

    async getGridList() {
      this.loading = true
      const { datapermissionMap } = Vue.ls.get(USER_INFO)
      const res1 = await postAction('/Sql2ApiCall/call/4028809589b9138c0189b933fa500001', {
        PARAMCODE: 'D',
        PAGECODE: 'root',
      })
      const jsonRes = JSON.parse(res1.result)
      const curDate = jsonRes.data.length ? jsonRes.data[0].value : '20230910'

      let params = {
        dayId: curDate || '20230910',
        type: '1001',
        // orgRank: this.permissionOrgCode,
      }
      const gridIdList = localStorage.getItem('$gridIdList')
      params = gridIdList
        ? {
            ...params,
            gridId: gridIdList,
          }
        : {
            ...params,
            orgRank: this.permissionOrgCode,
            depId: datapermissionMap[0].key,
          }
      const res = await postAction('/Sql2ApiCall/call/0500a9498233148c0182b53b0a030071', params)
      if (res.success) {
        let data = JSON.parse(res.result).data
        this.gridList = data
        this.formatList2Tree(data)
      }
      this.loading = false
    },
    formatList2Tree(data) {
      const parLevel = this.permissionOrgCode.split('/').length
      const areaMap = {}
      const cityMap = {}
      const gridMap = {}

      for (const item of data) {
        if (!(item.AREA_NO in areaMap)) {
          areaMap[item.AREA_NO] = {
            title: item.AREA_DESC,
            key: item.AREA_NO,
            selectable: false,
            children: [],
          }
        }
        if (!(item.CITY_NO in cityMap)) {
          cityMap[item.CITY_NO] = {
            title: item.CITY_DESC,
            key: item.CITY_NO,
            selectable: false,
            children: [],
          }
          areaMap[item.AREA_NO].children.push(cityMap[item.CITY_NO])
        }
        if (!(item.GRID_ID in gridMap)) {
          gridMap[item.GRID_ID] = {
            title: item.GRID_NAME,
            key: item.GRID_ID,
            orgCode: item.ORGRANK,
            type: item.MARKET_TYPE_DESC,
          }
          cityMap[item.CITY_NO].children.push(gridMap[item.GRID_ID])
        }
      }

      if (parLevel == 1) {
        this.formatTreeData = Object.values(areaMap)
      } else if (parLevel == 2) {
        this.formatTreeData = Object.values(cityMap)
      } else if (parLevel == 3) {
        this.formatTreeData = Object.values(gridMap)
      } else {
        this.formatTreeData = [
          {
            title: data[0].GRID_NAME,
            key: data[0].GRID_ID,
            orgCode: data[0].ORGRANK,
            type: data[0].MARKET_TYPE_DESC,
          },
        ]
      }
      this.treeData = this.formatTreeData
    },
    handleOpe(type) {
      if (type === 'submit') {
        if ('key' in this.selectdedNode) {
          const { key, title } = this.selectdedNode
          Vue.prototype.$gridId = key
          localStorage.setItem('$gridId', key)
          localStorage.setItem('$dataPermission', key)
          localStorage.setItem('$GRID_NAME', title)
          localStorage.setItem('$dialogFinish', true)
          localStorage.setItem('$openSelectGridPage', 'finish')
          Vue.ls.set('VIRTUAL_USER_ORGCODE', this.selectdedNode.orgCode || this.selectdedNode.key)
        } else {
          Toast('请选择营服!')
          return
        }
      }
      // 没有选择 营服 不可以退出此页面
      if (type === 'cancel' && (!localStorage.getItem('$gridId') || !localStorage.getItem('$GRID_NAME'))) {
        Toast('请选择营服!')
        return
      }
      if (process.env.NODE_ENV == 'production') {
        const isZWT = UA && /ipumobile/.test(UA)
        if (isZWT) {
          window.WadeMobile && window.WadeMobile.closeH5()
          return
        }
        boncAppEngine.shutdown()
        this.$open('/publicline/index')
      } else {
        this.$open('/publicline/index')
      }
    },
  },
}
</script>

<style lang="less" scoped>
@import '~@assets/less/reconsitution/common.less';
.GdwyyAppSelectGrid {
  background: #fff;
  min-height: 100vh;
  box-sizing: border-box;
}
.normal-list {
  box-sizing: border-box;
  min-height: 300px;
}
.selected-grid {
  margin-bottom: 6px;
  padding: 15px 15px 0 15px;
  box-sizing: border-box;

  .selected-grid-name {
    color: #f50;
  }
}
.input-s {
  margin-top: 10px;
}
.popup-ope {
  margin-bottom: 15px;
}
</style>